#!/usr/bin/env python3

import argparse
import os
import re

parser = argparse.ArgumentParser(description="Rename a CMake target. Opperates on the current directory.")

parser.add_argument("old", help="the target to rename", type=str)
parser.add_argument("new", help="the new target name", type=str)

args = parser.parse_args()

print(args.old)
print(args.new)

def editfile(f, old, new):
    contents = f.read()

    f.seek(0)

    contents = re.sub("([^\w.])" + old + "([^\w.])", r"\1" + new + r"\2", contents) 

    f.write(contents)

    f.truncate()

for dirpath, dirname, filenames in os.walk("."):
    for filename in filenames:
        if filename.endswith("CMakeLists.txt"):
            with open(dirpath +"/" + filename, "r+") as f:
                editfile(f, args.old, args.new)
